package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"mbook/models"
	"mbook/utils"
	"time"
)

type SearchController struct {
	BaseController
}

func (c *SearchController) Search() {
	c.TplName = "search/search.html"
}

func (c *SearchController) Result() {
	var ids []int
	totalRows := 0
	now := time.Now()

	keyword := c.GetString("wd")
	// 如果关键字为空则跳到搜索页
	if "" == keyword {
		c.Redirect(beego.URLFor("SearchController.Search"), 302)
	}

	tab := c.GetString("tab", "doc")
	page, _ := c.GetInt("page", 0)

	isSearchDoc := false
	if "doc" == tab {
		isSearchDoc = true
	}

	if page < 1 {
		page = 1
	}
	size := 10

	if isSearchDoc {
		// 搜索文档
	} else {
		// 搜索书籍的所有ID
		books, count, err := models.NewBook().SearchBook(keyword, page, size)
		totalRows = count
		if err != nil {
			beego.Error(err.Error())
		} else {
			for _, book := range books {
				ids = append(ids, book.BookId)
			}
		}
	}

	// 根据ID获取book详情内容
	if len(ids) > 0 {
		if isSearchDoc {

		} else {
			c.Data["Books"], _ = models.NewBook().GetBooksByIds(ids)
		}
	}

	c.Data["totalRows"] = totalRows
	if totalRows > size { // 需要分页
		if totalRows > 1000 {
			totalRows = 1000
		}

		urlSuffix := fmt.Sprintf("&tab=%v&wd=%v", tab, keyword)
		html := utils.NewPaginations(4, totalRows, size, page, beego.URLFor("SearchController.Result"), urlSuffix)
		c.Data["PageHtml"] = html
	} else {
		c.Data["PageHtml"] = ""
	}

	c.Data["SpendTime"] = fmt.Sprintf("%.3f", time.Since(now).Seconds())
	c.Data["Wd"] = keyword
	c.Data["Tab"] = tab
	c.TplName = "search/result.html"
}
